Generate a square matrix with elements in spiral orderΒΆ
Generate (given an integer N) a square matrix
filled with elements from 1 to N^2 in spiral order.
Expected output:
[
[1, 2, 3],
[8, 9, 4],
[7, 6, 5]
]
def generateMatrix(N):
if N <= 0:
return []
matrix = [row[:] for row in [[0] * N] * N]
row_st = 0
row_ed = N - 1
col_st = 0
col_ed = N - 1
current = 1
while (True):
if current > N * N:
break
for c in range (col_st, col_ed + 1):
matrix[row_st][c] = current
current += 1
row_st += 1
for r in range (row_st, row_ed + 1):
matrix[r][col_ed] = current
current += 1
col_ed -= 1
for c in range (col_ed, col_st - 1, -1):
matrix[row_ed][c] = current
current += 1
row_ed -= 1
for r in range (row_ed, row_st - 1, -1):
matrix[r][col_st] = current
current += 1
col_st += 1
return matrix
# test
print(list(generateMatrix(3)))
Output:
[
[1, 2, 3],
[8, 9, 4],
[7, 6, 5]
]